package com.origin.src.transaction;

import com.origin.src.ApplicationTool;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import javax.xml.crypto.Data;

@ComponentScan(value = {"com.origin.src.datasource", "com.origin.src.transaction"})
@Configuration
@EnableTransactionManagement
@EnableAspectJAutoProxy(exposeProxy = true)
public class TransactionApp {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(TransactionApp.class);
        ApplicationTool.printBean(app);
        TransactionBean transactionBean = app.getBean(TransactionBean.class);
        transactionBean.test();
        System.out.println(app.getBean(DataSource.class));

    }

    @Bean("TransactionDataSource")
    @ConditionalOnMissingBean(DataSource.class)
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/xdb?serverTimezone=GMT%2B8&autoReconnect=true&failOverReadOnly=false&autoReconnect=true&autoReconnectForPools=true");
        hikariConfig.setUsername("xin");
        hikariConfig.setPassword("xin");
        hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
        hikariConfig.setMaximumPoolSize(8);
        hikariConfig.setMinimumIdle(0);
        hikariConfig.setPoolName("TransactionDataSource");
        return new HikariDataSource(hikariConfig);
    }


    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}
